package com.ebelter.btcomlib.views;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;

import android.graphics.Paint;

import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;

import android.view.animation.DecelerateInterpolator;

import com.ebelter.btcomlib.R;
import com.ebelter.btcomlib.utils.StringUtils;
import com.ebelter.btcomlib.utils.TimeUtils;
import com.ebelter.btcomlib.utils.log.LogUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



/**
 * 自定义折线图
 * Created by xiaoyunfei on 16/11/29.
 */
public class ChartView extends View {
    public static final String TAG = "ChartView";
    //xy坐标轴颜色
    private int xylinecolor = 0xffe2e2e2;
    //xy坐标轴宽度
    private int xylinewidth = dpToPx(1);
    //xy坐标轴文字颜色
    private int xytextcolor = 0xff7e7e7e;
    //xy坐标轴文字大小
    private int xytextsize = spToPx(12);
    //折线图中折线的颜色
    private int linecolor = 0xff02bbb7;
    //折线图中折线的2颜色
    private int linecolor2 = 0xff02bbb7;
    //x轴各个坐标点水平间距
    private int interval = dpToPx(300);
    //背景颜色
    private int bgcolor = 0xffffffff;
    //是否在ACTION_UP时，根据速度进行自滑动，没有要求，建议关闭，过于占用GPU
    private boolean isScroll = false;
    //绘制XY轴坐标对应的画笔
    private Paint xyPaint;
    //绘制XY轴的文本对应的画笔
    private Paint xyTextPaint;
    //画折线对应的画笔
    private Paint linePaint;
    private Paint linePaint2;
    private int width;
    private int height;
    //x轴的原点坐标
    private int xOri;
    //y轴的原点坐标
    private int yOri;
    //第一个点X的坐标
    private float xInit;
    //第一个点对应的最大Y坐标
    private float maxXInit;
    //第一个点对应的最小X坐标
    private float minXInit;
    //x轴坐标对应的数据
    private List<String> xValue = new ArrayList<>();
    //y轴坐标对应的数据
    private List<Integer> yValue = new ArrayList<>();
    //折线对应的数据
    private Map<String, Integer> value = new HashMap<>();
    private Map<String, Integer> value2 = new HashMap<>();



    //是否显示区域
    private boolean isDisZone(int index){
        LogUtils.i("isDisZone","interval="+interval+"----index="+index+"---xInit="+xInit);
        boolean result;
        if (Math.abs(interval*index-xInit)<2000){
            result = true;
        }else {
            result = false;
        }


        LogUtils.i("isDisZone","interval="+interval+"----index="+index+"---xInit="+xInit+"----result="+result+"----相差的值="+(interval*index-xInit));

        return result;
    }



    //打印信息
    private void printInfo(String weizhi){

        LogUtils.i(TAG,weizhi+"---width="+width+"---height="+height+"---xOri="+xOri+"--" +
                "-yOri="+yOri+"---xInit="+xInit+"---interval="+interval+"---maxXInit="+maxXInit+"---minXInit="+minXInit
        +"---xValue.size="+xValue.size()+"---yValue.size="+yValue.size()+"---value.size="+value.size()
        +"---value2.size="+(value2!=null?value2.size():"null"));
    }

    //点击的点对应的X轴的第几个点，默认1
    private int selectIndex = 1;
    //X轴刻度文本对应的最大矩形，为了选中时，在x轴文本画的框框大小一致
    private Rect xValueRect;
    //速度检测器
    private VelocityTracker velocityTracker;

    public ChartView(Context context) {
        this(context, null);
    }

    public ChartView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }


    //private boolean isfirst=true;
    public ChartView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);
        initPaint();


        for (int i = 0; i < 10; i++) {
            xValue.add("");
            value.put("", 500);//60--240
            value2.put("", 500);//60--240
        }

        for (int i = 0; i < 7; i++) {
            yValue.add(i *50);
        }
        //isfirst = true;

    }

//    public void setXValue(int count){
//        for (int i=0;i<count;i++){
//            xValue.add("1");
//        }
//        LogUtils.i(TAG,"xValue.size()="+xValue.size());
//    }

    /**
     * 初始化畫筆
     */
    private void initPaint() {
        xyPaint = new Paint();
        xyPaint.setAntiAlias(true);
        xyPaint.setStrokeWidth(xylinewidth);
        xyPaint.setStrokeCap(Paint.Cap.ROUND);
        xyPaint.setColor(xylinecolor);

        xyTextPaint = new Paint();
        xyTextPaint.setAntiAlias(true);
        xyTextPaint.setTextSize(spToPx(10));
        //  xyTextPaint.setStrokeCap(Paint.Cap.ROUND);
        xyTextPaint.setColor(xytextcolor);
        //xyTextPaint.setStyle(Paint.Style.STROKE);

        linePaint = new Paint();
        linePaint.setAntiAlias(true);
        linePaint.setStrokeWidth(xylinewidth);
        //linePaint.setStrokeCap(Paint.Cap.ROUND);
        linePaint.setColor(linecolor);
        //linePaint.setStyle(Paint.Style.STROKE);

        linePaint2 = new Paint();
        linePaint2.setAntiAlias(true);
        linePaint2.setStrokeWidth(xylinewidth);
        //linePaint.setStrokeCap(Paint.Cap.ROUND);
        linePaint2.setColor(linecolor2);
        //linePaint.setStyle(Paint.Style.STROKE);
    }

    /**
     * 初始化
     */
    private void init(Context context, AttributeSet attrs, int defStyleAttr) {
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.chartView, defStyleAttr, 0);
        int count = array.getIndexCount();
        for (int i = 0; i < count; i++) {
            int attr = array.getIndex(i);
            if (attr==R.styleable.chartView_xylinecolor){
                xylinecolor = array.getColor(attr, xylinecolor);//xy坐标轴颜色
            }else if (attr==R.styleable.chartView_xylinewidth){//xy坐标轴宽度
                xylinewidth = (int) array.getDimension(attr, TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, xylinewidth, getResources().getDisplayMetrics()));
            }else if (attr==R.styleable.chartView_xytextcolor){//xy坐标轴文字颜色
                xytextcolor = array.getColor(attr, xytextcolor);
            }else if (attr==R.styleable.chartView_xytextsize){//xy坐标轴文字大小
                xytextsize = (int) array.getDimension(attr, TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, xytextsize, getResources().getDisplayMetrics()));
            }else if (attr==R.styleable.chartView_linecolor){//折线图中折线的颜色
                linecolor = array.getColor(attr, linecolor);
            }else if (attr==R.styleable.chartView_linecolor2){//折线图中折线的2颜色
                linecolor2 = array.getColor(attr, linecolor2);
            }else if (attr==R.styleable.chartView_interval){//x轴各个坐标点水平间距
                interval = (int) array.getDimension(attr, TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, interval, getResources().getDisplayMetrics()));
            }else if (attr==R.styleable.chartView_bgcolor){//背景颜色
                bgcolor = array.getColor(attr, bgcolor);
            }else if (attr==R.styleable.chartView_isScroll){//是否在ACTION_UP时，根据速度进行自滑动
                isScroll = array.getBoolean(attr, isScroll);
            }
        }
        array.recycle();

    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (changed) {
            //这里需要确定几个基本点，只有确定了xy轴原点坐标，第一个点的X坐标值及其最大最小值
            initBase();
        }

    }

    @Override
    protected void onDraw(Canvas canvas) {
        Log.i(TAG,"---onDraw--");

        canvas.drawColor(bgcolor);
        drawXY(canvas);



       // if (!isfirst){
            drawBrokenLineAndPoint(canvas);
            if (value2!=null&&value2.size()>0){
                drawBrokenLineAndPoint2(canvas);
            }
       // }
       // isfirst=false;

    }

//    //画测试线
//    private void drawTestLine(Canvas canvas) {
//        Paint paint=new Paint(Paint.ANTI_ALIAS_FLAG);
//        paint.setStyle(Paint.Style.STROKE);
//        paint.setStrokeWidth(5);
//        paint.setColor(Color.parseColor("#ff0000"));
//        Path path=new Path();
//        for (int i=0;i<10;i++){
//            path.lineTo(i*250,-250);
//        }
//        canvas.drawPath(path,paint);
//    }

    private void initBase() {
        width = getWidth();
        height = getHeight();
        //Y轴文本最大宽度
//        float textYWdith = getTextBounds("000", xyTextPaint).width();
//
//        for (int i = 0; i < yValue.size(); i++) {//求取y轴文本最大的宽度
//            float temp = getTextBounds(yValue.get(i) + "", xyTextPaint).width();
//            if (temp > textYWdith)
//                textYWdith = temp;
//        }
       // int dp2 = dpToPx(2);
        int dp4 = dpToPx(4);
        int dp6 = dpToPx(6);
        //xOri = (int) (dp2 + textYWdith + dp2 + xylinewidth);//dp2是y轴文本距离左边，以及距离y轴的距离
        xOri = 0;//dp2是y轴文本距离左边，以及距离y轴的距离

//            //X轴文本最大高度
        xValueRect = getTextBounds("000", xyTextPaint);
        float textXHeight = xValueRect.height();
        for (int i = 0; i < xValue.size(); i++) {//求取x轴文本最大的高度
            Rect rect = getTextBounds(xValue.get(i) + "", xyTextPaint);
            if (rect.height() > textXHeight)
                textXHeight = rect.height();
            if (rect.width() > xValueRect.width())
                xValueRect = rect;
        }
        yOri = (int) (height - dp4 - textXHeight*2 - dp6 - xylinewidth*2);//dp3是x轴文本距离底边，dp2是x轴文本距离x轴的距离
        xInit = interval + xOri;
        minXInit = width - (width - xOri) * 0.1f - interval * (xValue.size() - 1);//减去0.1f是因为最后一个X周刻度距离右边的长度为X轴可见长度的10%
        maxXInit = xInit;
       // printInfo("initBase");
    }

    /**
     * 绘制折线和折线交点处对应的点
     */
    private void drawBrokenLineAndPoint(Canvas canvas) {
        if (xValue.size() <= 0)
            return;
        //重新开一个图层
        int layerId = canvas.saveLayer(0, 0, width, height, null, Canvas.ALL_SAVE_FLAG);
        drawBrokenLine(canvas);
        drawBrokenPoint(canvas);

        // 将折线超出x轴坐标的部分截取掉
        linePaint.setStyle(Paint.Style.FILL);
        linePaint.setColor(bgcolor);
        linePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
        RectF rectF = new RectF(0, 0, xOri, height);
        canvas.drawRect(rectF, linePaint);
        linePaint.setXfermode(null);
        //保存图层
        canvas.restoreToCount(layerId);
    }

    /**
     * 绘制折线和折线交点处对应的点
     */
    private void drawBrokenLineAndPoint2(Canvas canvas) {
        if (xValue.size() <= 0)
            return;
        //重新开一个图层
        int layerId = canvas.saveLayer(0, 0, width, height, null, Canvas.ALL_SAVE_FLAG);
        drawBrokenLine2(canvas);
        drawBrokenPoint2(canvas);

        // 将折线超出x轴坐标的部分截取掉
        linePaint2.setStyle(Paint.Style.FILL);
        linePaint2.setColor(bgcolor);
        linePaint2.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
        RectF rectF = new RectF(0, 0, xOri, height);
        canvas.drawRect(rectF, linePaint2);
        linePaint2.setXfermode(null);
        //保存图层
        canvas.restoreToCount(layerId);
    }

    /**
     * 绘制折线对应的点
     */
    private void drawBrokenPoint(Canvas canvas) {
        float dp2 = dpToPx(2);
        float dp4 = dpToPx(4);
        float dp7 = dpToPx(7);
        //绘制节点对应的原点
        for (int i = 0; i < xValue.size(); i++) {
            float x = xInit + interval * i;
            float y = yOri - yOri * (1 - 0.1f) * value.get(xValue.get(i)) / yValue.get(yValue.size() - 1);
            //绘制选中的点
            // if (i == selectIndex - 1) {
            linePaint.setStyle(Paint.Style.FILL);
            linePaint.setColor(linecolor);
            // canvas.drawCircle(x, y, dp7, linePaint);
            // linePaint.setColor(0xff81dddb);
            // canvas.drawCircle(x, y, dp4, linePaint);
            drawFloatTextBox(canvas, x, y - dp7, value.get(xValue.get(i)));
            //}
            //绘制普通的节点
            linePaint.setStyle(Paint.Style.FILL);
            linePaint.setColor(linecolor);
            canvas.drawCircle(x, y, dp2, linePaint);
            linePaint.setStyle(Paint.Style.STROKE);
            linePaint.setColor(linecolor);
            canvas.drawCircle(x, y, dp2, linePaint);

        }
    }

    /**
     * 绘制折线对应的点
     */
    private void drawBrokenPoint2(Canvas canvas) {

        float dp2 = dpToPx(2);
        float dp7 = dpToPx(7);
        //绘制节点对应的原点
        for (int i = 0; i < xValue.size(); i++) {
            float x = xInit + interval * i;
            float y = yOri - yOri * (1 - 0.1f) * value2.get(xValue.get(i)) / yValue.get(yValue.size() - 1);
            //绘制选中的点
            // if (i == selectIndex - 1) {
            linePaint2.setStyle(Paint.Style.FILL);
            linePaint2.setColor(linecolor2);
            // canvas.drawCircle(x, y, dp7, linePaint);
            // linePaint.setColor(0xff81dddb);
            // canvas.drawCircle(x, y, dp4, linePaint);
            drawFloatTextBox2(canvas, x, y - dp7, value2.get(xValue.get(i)));
            //}
            //绘制普通的节点
            linePaint2.setStyle(Paint.Style.FILL);
            linePaint2.setColor(linecolor2);
            canvas.drawCircle(x, y, dp2, linePaint2);
            linePaint2.setStyle(Paint.Style.STROKE);
            linePaint2.setColor(linecolor2);
            canvas.drawCircle(x, y, dp2, linePaint2);

        }
    }

    /**
     * 绘制显示Y值的浮动框
     */
    private void drawFloatTextBox(Canvas canvas, float x, float y, int text) {
        int dp6 = dpToPx(6);
        int dp18 = dpToPx(18);
//        //p1
//        Path path = new Path();
//        path.moveTo(x, y);
//        //p2
//        path.lineTo(x - dp6, y - dp6);
//        //p3
//        path.lineTo(x - dp18, y - dp6);
//        //p4
//        path.lineTo(x - dp18, y - dp6 - dp18);
//        //p5
//        path.lineTo(x + dp18, y - dp6 - dp18);
//        //p6
//        path.lineTo(x + dp18, y - dp6);
//        //p7
//        path.lineTo(x + dp6, y - dp6);
//        //p1
//        path.lineTo(x, y);
//        canvas.drawPath(path, linePaint);
        linePaint.setColor(linecolor);
        linePaint.setTextSize(spToPx(10));
        Rect rect = getTextBounds(text + "", linePaint);


        float yResult=y - dp6 - (dp18 - rect.height()) / 2;
        //   float yResult=y + (dp18 + rect.height());
//        if (y<height/2){
//            yResult=y - dp6 - (dp18 - rect.height()) / 2;//111
//        }else {
//            yResult=y + dp6 + (dp18 + rect.height()) / 2;
//        }

        canvas.drawText(text + "", x - rect.width() / 2, yResult, linePaint);
    }

    private void drawFloatTextBox2(Canvas canvas, float x, float y, int text) {
       // int dp6 = dpToPx(6);
        int dp18 = dpToPx(18);

        linePaint2.setColor(linecolor2);
        linePaint2.setTextSize(spToPx(10));
        Rect rect = getTextBounds(text + "", linePaint2);


        // float yResult=y - dp6 - (dp18 - rect.height()) / 2;
        float yResult=y + (dp18 + rect.height());
//        if (y<height/2){
//            yResult=y - dp6 - (dp18 - rect.height()) / 2;//111
//        }else {
//            yResult=y + dp6 + (dp18 + rect.height()) / 2;
//        }

        canvas.drawText(text + "", x - rect.width() / 2, yResult, linePaint2);
    }

    /**
     * 绘制折线
     */
    private void drawBrokenLine(Canvas canvas) {
        linePaint.setStyle(Paint.Style.STROKE);
        linePaint.setColor(linecolor);
        //绘制折线
        //Path path = new Path();
        float x1 = xInit;
        float y1 = yOri - yOri * (1 - 0.1f) * value.get(xValue.get(0)) / yValue.get(yValue.size() - 1);
        //path.moveTo(x1, y1);

        float x2;
        float y2;

   //     LogUtils.i("drawBrokenLine","A------x1 ="+x1+"----y1="+y1);
        for (int i = 1; i < xValue.size(); i++) {
            x2 = xInit + interval * i;
            y2 = yOri - yOri * (1 - 0.1f) * value.get(xValue.get(i)) / yValue.get(yValue.size() - 1);

           // if (isDisZone(i)){
                canvas.drawLine(x1,y1,x2,y2,linePaint);
            //}

            //path.lineTo(x2, y2);
            //LogUtils.i("drawBrokenLine","B------x2 ="+x2+"----y2="+y2);
            x1=x2;
            y1=y2;
        }
      //  canvas.drawPath(path, linePaint);


    }
    private void drawBrokenLine2(Canvas canvas) {
        linePaint2.setStyle(Paint.Style.STROKE);
        linePaint2.setColor(linecolor2);
        float x1 = xInit;
        float y1 = yOri - yOri * (1 - 0.1f) * value2.get(xValue.get(0)) / yValue.get(yValue.size() - 1);
        //path.moveTo(x1, y1);

        float x2;
        float y2;

     //   LogUtils.i("drawBrokenLine2","A------x1 ="+x1+"----y1="+y1);
        for (int i = 1; i < xValue.size(); i++) {
            x2 = xInit + interval * i;
            y2 = yOri - yOri * (1 - 0.1f) * value2.get(xValue.get(i)) / yValue.get(yValue.size() - 1);

            // if (isDisZone(i)){
            canvas.drawLine(x1,y1,x2,y2,linePaint2);
            //}

            //path.lineTo(x2, y2);
           // LogUtils.i("drawBrokenLine2","B------x2 ="+x2+"----y2="+y2);
            x1=x2;
            y1=y2;
        }
    }


    public boolean isDisplayXDateFlag = false;



    /**
     * 绘制XY坐标
     */
    private void drawXY(Canvas canvas) {
        int length = dpToPx(4);//刻度的长度
        //绘制Y坐标
        // canvas.drawLine(xOri - xylinewidth / 2, 0, xOri - xylinewidth / 2, yOri, xyPaint);
        //绘制y轴箭头
        xyPaint.setStyle(Paint.Style.STROKE);
        //Path path;

        //绘制X轴坐标
        canvas.drawLine(xOri, yOri + xylinewidth / 2, width, yOri + xylinewidth / 2, xyPaint);
        //绘制x轴箭头
       // xyPaint.setStyle(Paint.Style.STROKE);
       // path = new Path();
        //整个X轴的长度
        float xLength = xInit + interval * (xValue.size() - 1) + (width - xOri) * 0.1f;
        if (xLength < width)
            xLength = width;
       // path.moveTo(xLength - dpToPx(12), yOri + xylinewidth / 2 - dpToPx(5));
      //  path.lineTo(xLength - xylinewidth / 2, yOri + xylinewidth / 2);
      //  path.lineTo(xLength - dpToPx(12), yOri + xylinewidth / 2 + dpToPx(5));
       // canvas.drawPath(path, xyPaint);
        //绘制x轴刻度

       // printInfo("drawXY");

        for (int i = 0; i < xValue.size(); i++) {
            float x = xInit + interval * i;
            if (x >= xOri) {//只绘制从原点开始的区域
                xyTextPaint.setColor(xytextcolor);
                canvas.drawLine(x, yOri, x, yOri - length, xyPaint);//画X轴上的刻度值

                //LogUtils.i(TAG,"xValue.size()="+xValue.size()+"---xOri="+xOri+"--x="+x+"---yOri="+yOri+"---stopY="+(yOri - length));

                //绘制X轴文本
                String text = xValue.get(i);
                String[] textStrs=text.split(" ");//2018-08-08 08:08:08

                String date ="";
                if (textStrs.length>0){
                   // date=StringUtils.subString(textStrs[0],5);
                    date=textStrs[0];
                    if (!StringUtils.isEmpty(date)&&date.length()==10){
                        date=TimeUtils.formatDateStampString1(getContext(),TimeUtils.parseFormatter3Time(date).getTime());
                    }

                }



                String time = "";
                if (textStrs.length>1){
                    time=StringUtils.subString(textStrs[1],0,5);
                }

             //   LogUtils.i(TAG,"xValue.size()="+xValue.size()+"---xOri="+xOri+"--x="+x+"---yOri="+yOri+"---stopY="+(yOri - length)+"---xValue.get(i="+i+")="+text);

                Rect daterect = getTextBounds(date, xyTextPaint);
                Rect timerect = getTextBounds(time, xyTextPaint);


                // String disTime1=StringUtils.subString(bean.getTestDate(),5,10);
                // String disTime2=StringUtils.subString(bean.getTestDate(),11,16);
                //  String disTime2=StringUtils.subString(bean.getTestDate(),10,16);

                if (isDisplayXDateFlag){
                    canvas.drawText(date, 0, date.length(), x - daterect.width() / 2, yOri + xylinewidth + dpToPx(2) + daterect.height(), xyTextPaint);
                    canvas.drawText(time, 0, time.length(), x - timerect.width() / 2, yOri + xylinewidth + dpToPx(6) + timerect.height()*2, xyTextPaint);
                }else {
                    canvas.drawText(time, 0, time.length(), x - timerect.width() / 2, yOri + xylinewidth + dpToPx(2) + timerect.height(), xyTextPaint);
                }



            }
        }
    }

    private float startX;

    int mPosX;
    int mPosY;

    int mCurrentPosX;
    int mCurrentPosY;
    //public int touchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (isScrolling)
            return super.onTouchEvent(event);

       // initBase();
      //  this.getParent().requestDisallowInterceptTouchEvent(true);//当该view获得点击事件，就请求父控件不拦截事件
        obtainVelocityTracker(event);
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mPosX = (int)event.getX();
                mPosY = (int)event.getY();

                LogUtils.i(TAG,"---onTouchEvent");
                startX = event.getX();
                break;
            case MotionEvent.ACTION_MOVE:
                LogUtils.i(TAG,"---ACTION_MOVE");

                mCurrentPosX = (int)event.getX()-mPosX;
                mCurrentPosY = (int)event.getY()-mPosY;
                mPosX = (int)event.getX();
                mPosY = (int)event.getY();


                if (interval * xValue.size() > width - xOri) {//当期的宽度不足以呈现全部数据
                    float dis = event.getX() - startX;
                    startX = event.getX();
                    if (xInit + dis < minXInit) {
                        xInit = minXInit;
                    } else if (xInit + dis > maxXInit) {
                        xInit = maxXInit;
                    } else {
                        xInit = xInit + dis;
                    }
                    invalidate();
                }
                break;
            case MotionEvent.ACTION_UP:
                LogUtils.i(TAG,"---ACTION_UP");
                clickAction(event);
                scrollAfterActionUp();
                this.getParent().requestDisallowInterceptTouchEvent(false);
                recycleVelocityTracker();
                break;
            case MotionEvent.ACTION_CANCEL:
                LogUtils.i(TAG,"---ACTION_CANCEL");
                this.getParent().requestDisallowInterceptTouchEvent(false);
                recycleVelocityTracker();
                break;
        }

        if (Math.abs(mCurrentPosX)>2&&Math.abs(mCurrentPosX)>Math.abs(mCurrentPosY)) {

            LogUtils.i(TAG, "--------左右滑动");
            this.getParent().requestDisallowInterceptTouchEvent(true);//当该view获得点击事件，就请求父控件不拦截事件

        }else if (Math.abs(mCurrentPosY)>2&&Math.abs(mCurrentPosX)<Math.abs(mCurrentPosY)) {

            LogUtils.i(TAG, "-------------------上下滑动");
            this.getParent().requestDisallowInterceptTouchEvent(false);//当该view获得点击事件，就请求父控件不拦截事件

        }


        return true;
    }

    public void src2end(){
        xInit = minXInit;
        invalidate();
    }


    //是否正在滑动
    private boolean isScrolling = false;

    /**
     * 手指抬起后的滑动处理
     */
    private void scrollAfterActionUp() {
        if (!isScroll)
            return;
        final float velocity = getVelocity();
        float scrollLength = maxXInit - minXInit;
        if (Math.abs(velocity) < 10000)//10000是一个速度临界值，如果速度达到10000，最大可以滑动(maxXInit - minXInit)
            scrollLength = (maxXInit - minXInit) * Math.abs(velocity) / 10000;
        ValueAnimator animator = ValueAnimator.ofFloat(0, scrollLength);
        animator.setDuration((long) (scrollLength / (maxXInit - minXInit) * 1000));//时间最大为1000毫秒，此处使用比例进行换算
        animator.setInterpolator(new DecelerateInterpolator());
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                float value = (float) valueAnimator.getAnimatedValue();
                if (velocity < 0 && xInit > minXInit) {//向左滑动
                    if (xInit - value <= minXInit)
                        xInit = minXInit;
                    else
                        xInit = xInit - value;
                } else if (velocity > 0 && xInit < maxXInit) {//向右滑动
                    if (xInit + value >= maxXInit)
                        xInit = maxXInit;
                    else
                        xInit = xInit + value;
                }
                invalidate();
            }
        });
        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {
                isScrolling = true;
            }

            @Override
            public void onAnimationEnd(Animator animator) {
                isScrolling = false;
            }

            @Override
            public void onAnimationCancel(Animator animator) {
                isScrolling = false;
            }

            @Override
            public void onAnimationRepeat(Animator animator) {

            }
        });
        animator.start();

    }

    /**
     * 获取速度
     */
    private float getVelocity() {
        if (velocityTracker != null) {
            velocityTracker.computeCurrentVelocity(1000);
            return velocityTracker.getXVelocity();
        }
        return 0;
    }

    /**
     * 点击X轴坐标或者折线节点
     */
    private void clickAction(MotionEvent event) {
        int dp8 = dpToPx(8);
        float eventX = event.getX();
        float eventY = event.getY();
        for (int i = 0; i < xValue.size(); i++) {
            //节点
            float x = xInit + interval * i;
            float y = yOri - yOri * (1 - 0.1f) * value.get(xValue.get(i)) / yValue.get(yValue.size() - 1);
            if (eventX >= x - dp8 && eventX <= x + dp8 &&
                    eventY >= y - dp8 && eventY <= y + dp8 && selectIndex != i + 1) {//每个节点周围8dp都是可点击区域
                selectIndex = i + 1;
                invalidate();
                return;
            }
            //X轴刻度
            String text = xValue.get(i);
            Rect rect = getTextBounds(text, xyTextPaint);
            x = xInit + interval * i;
            y = yOri + xylinewidth + dpToPx(2);
            if (eventX >= x - rect.width() / 2 - dp8 && eventX <= x + rect.width() + dp8 / 2 &&
                    eventY >= y - dp8 && eventY <= y + rect.height() + dp8 && selectIndex != i + 1) {
                selectIndex = i + 1;
                invalidate();
                return;
            }
        }
    }


    /**
     * 获取速度跟踪器
     */
    private void obtainVelocityTracker(MotionEvent event) {
        if (!isScroll)
            return;
        if (velocityTracker == null) {
            velocityTracker = VelocityTracker.obtain();
        }
        velocityTracker.addMovement(event);
    }

    /**
     * 回收速度跟踪器
     */
    private void recycleVelocityTracker() {
        if (velocityTracker != null) {
            velocityTracker.recycle();
            velocityTracker = null;
        }
    }

    public int getSelectIndex() {
        return selectIndex;
    }

    public void setSelectIndex(int selectIndex) {
        this.selectIndex = selectIndex;
        invalidate();
    }

    public void setxValue(List<String> xValue) {
        this.xValue = xValue;
    }

    public void setyValue(List<Integer> yValue) {
        this.yValue = yValue;
        invalidate();
    }

    public void setValue(Map<String, Integer> value) {
        this.value = value;
        invalidate();
    }

    public void setValue(Map<String, Integer> value,Map<String, Integer> value2,  List<String> xValue, List<Integer> yValue) {
        this.value = value;
        this.value2 = value2;
        this.xValue = xValue;
        this.yValue = yValue;
        initBase();
        invalidate();
    }

    public void clear(){
        value.clear();
        if (value2!=null)value2.clear();
        xValue.clear();
        yValue.clear();
        initBase();
        invalidate();
    }

    public List<String> getxValue() {
        return xValue;
    }

    public List<Integer> getyValue() {
        return yValue;
    }

    public Map<String, Integer> getValue() {
        return value;
    }

    /**
     * 获取丈量文本的矩形
     */
    private Rect getTextBounds(String text, Paint paint) {
        Rect rect = new Rect();
        paint.getTextBounds(text, 0, text.length(), rect);
        return rect;
    }

    /**
     * dp转化成为px
     */
    private int dpToPx(int dp) {
        float density = getContext().getResources().getDisplayMetrics().density;
        return (int) (dp * density + 0.5f * (dp >= 0 ? 1 : -1));
    }

    /**
     * sp转化为px
     */
    private int spToPx(int sp) {
        float scaledDensity = getContext().getResources().getDisplayMetrics().scaledDensity;
        return (int) (scaledDensity * sp + 0.5f * (sp >= 0 ? 1 : -1));
    }
}

